package com.isias.system.Controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.isias.common.result.Result;
import com.isias.model.dto.CourseDto;
import com.isias.model.dto.CourseWithStar;
import com.isias.model.dto.PingLunDto;
import com.isias.model.dto.UserAndIdDto;
import com.isias.model.system.SysUser;
import com.isias.model.vo.CourseVo;
import com.isias.model.vo.SelectCourseVo;
import com.isias.model.vo.Star;
import com.isias.system.Config.WenJianConfig;
import com.isias.system.Service.IAuthenticationFacade;
import com.isias.system.service.CourseService;
import com.isias.system.service.SysUserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/course/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private IAuthenticationFacade authenticationFacade; //获取当前用户对象类

    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询全部，兼条件查询
     * @param courseVo
     * @return
     */
    @GetMapping
    public Result SelectAll(SelectCourseVo courseVo){
        List<CourseDto> dtos = courseService.SelectAll(courseVo);
        return Result.ok(dtos);
    }

    /**
     * 查询我教的课(通过个人id查询，从Security取)
     * @param courseVo
     * @return
     */
    @GetMapping("/TeachCourse")
    public Result SelectAllById(SelectCourseVo courseVo){
        List<CourseDto> dtos = courseService.SelectAllById(GetId(),courseVo);
        return Result.ok(dtos);
    }

    /**
     * 获取所有课程，并按平均评星倒叙排序
     * @return
     */
    @GetMapping("CourseWithStar")
    public Result SelectAllStar(){
        List<CourseWithStar> dtos = courseService.SelectAllStar();
        return Result.ok(dtos);
    }

    /**
     * 获取课程的评论
     * @return
     */
    @GetMapping("PingLun/{courseId}")
    public Result PingLun(@PathVariable String courseId){
        List<PingLunDto> dtos = courseService.GetPingLun(courseId);
        return Result.ok(dtos);
    }

    /**
     * 查询我学的课(通过个人id查询，从Security取)
     * @param courseVo
     * @return
     */
    @GetMapping("/MyCourse")
    public Result SelectMyCourse(SelectCourseVo courseVo){
        List<CourseDto> dtos = courseService.SelectMyCourse(GetId(),courseVo);
        return Result.ok(dtos);
    }

    /***
     * 退课操作
     * @param id
     * @return
     */
    @DeleteMapping("/RemoveMyCourse/{id}")
    public Result RemoveMyCourse(@PathVariable String id){
        if (courseService.DeleteCourseToMe(GetId(),id)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /***
     * 添加到我的课程
     * @param id
     * @return
     */
    @GetMapping("/AddCourseToMe/{id}")
    public Result AddCourseToMe(@PathVariable String id){
        if (courseService.AddCourseToMe(GetId(),id)) {
            return Result.ok();
        }
        return Result.fail();
    }


    /**
     * 查询单个，主要用于数据回显
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result SelectOne(@PathVariable String id){
        CourseDto dtos = courseService.SelectOne(id);
        return Result.ok(dtos);
    }

    /**
     * 插入
     * @param courseVo
     * @return
     */
    @PostMapping
    public Result Insert(@RequestBody CourseVo courseVo){
        //判断从前端传来的数据中是否携带教师id，如果没有教师id，则给教师id赋值为当前用户登录id
        if (courseVo.getTeacherId()==null||courseVo.getTeacherId().length()==0){
            courseVo.setTeacherId(GetId());
        }
        //在数据库中进行添加
        if (courseService.Add(courseVo)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 更新
     * @param courseVo
     * @return
     */
    @PutMapping
    public Result Updata(@RequestBody CourseVo courseVo){
        if (courseService.UpdataOneById(courseVo)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 删除单个
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result DeleteOne(@PathVariable String id){
        if (courseService.RemoveOneById(id)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     *根据id批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result DeleteOne(@RequestBody List<String> ids){
        if (courseService.RemoveByIds(ids)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 获取所有用户的id和name
     * @return
     */
    @GetMapping("/AllTeacher")
    public Result SelectAllUserAndId(){
        List<UserAndIdDto> list = courseService.SelectUserAndId();
        return Result.ok(list);
    }

    /**
     * 课程图片上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/coursePicture")
    public Result<Map<String,Object>> coursePicture(MultipartFile file) throws IOException {
        // 文件名称  时间日期+文件名_uuid+后缀
        String fileName = StrUtil.format("{}/{}_{}.{}", DateUtil.format(DateUtil.date(),"yyy/MM/dd"), FilenameUtils.getBaseName(file.getOriginalFilename()),DateUtil.format(new Date(),"yyyyMMdd")+ IdUtil.fastUUID(), FilenameUtils.getExtension(file.getOriginalFilename()));
        // 父目录
        String baseDir = WenJianConfig.getCoursePicturePath();
        //路径拼接
        File desc = new File(baseDir + File.separator + fileName);
        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        // 下载
        file.transferTo(desc);
        int dirLastIndex = WenJianConfig.getProfile().length() + 1;
        // 截取upload/下的名称存入数据库
        String currentDir = baseDir.substring(dirLastIndex);

        String picture = WenJianConfig.getUrl() + currentDir + "/" + fileName;
        Map<String, Object> map = new HashMap<>();
        // 将头像路径返回
        map.put("imgUrl",picture);
        return Result.ok(map);
    }
    /**
     * 对课程评价
     * @param courseId
     * @param star
     * @return
     */
    @PutMapping("Star/{courseId}")
    public Result Star(@PathVariable String courseId, @RequestBody Star star){
        if (courseService.Star(GetId(),courseId,star)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 获取课程的平均评分
     * @param courseId
     * @return
     */
    @GetMapping("GetStar/{courseId}")
    public Result GetStar(@PathVariable String courseId){
        return Result.ok(courseService.GetStar(courseId));
    }

    /**
     * 获取平均评星最多的课程
     * @return
     */
    @GetMapping("GetStarCourse")
    public Result GetStarCourse(){
        return Result.ok(courseService.GetStarCourse());
    }

    /**
     * 获取最多学习的课程
     * @return
     */
    @GetMapping("GetMostStudy")
    public Result GetMostStudy(){
        return Result.ok(courseService.GetMostStudy());
    }
    /**
     * 获取我对某个课程的评价(数据回显)
     * @param courseId
     * @return
     */
    @GetMapping("GetStarInfo/{courseId}")
    public Result GetStarInfo(@PathVariable String courseId){
        return Result.ok(courseService.GetStarInfo(GetId(),courseId));
    }

    /**
     * 获取当前登录用户的id抽取方法
     * @return
     */
    public String GetId(){
        // 获取当前登录用户
        Authentication authentication = authenticationFacade.getAuthentication();
        String username = authentication.getName();
        return sysUserService.GetIdByUsername(username);
    }

//    /**
//     * 创建这个类仅仅是为了得到当前用户的id
//     * @return
//     */
//    @GetMapping("/GetNowId")
//    public Result GetNowId(){
//        // 获取当前登录用户
//        Authentication authentication = authenticationFacade.getAuthentication();
//        String username = authentication.getName();
//        SysUser sysUser = sysUserService.GetUserByusername(username);
//        return Result.ok(sysUser.getId());
//    }

}
